<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">作业计划</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">生产工序</text>
          <picker
            mode="selector"
            :range="processOptions"
            range-key="text"
            :value="currentProcessIndex"
            @change="handleProcessChange"
            class="process-picker-container"
          >
            <view class="process-picker">
              <text class="process-display">{{
                currentProcess && currentProcess.processName
                  ? currentProcess.processName
                  : "请选择生产工序"
              }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- C. 查询/选择区 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="
              handleTimeChange('today');
              handleSearch();
            "
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'yesterday' }"
            @tap="
              handleTimeChange('yesterday');
              handleSearch();
            "
          >
            昨日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'tomorrow' }"
            @tap="
              handleTimeChange('tomorrow');
              handleSearch();
            "
          >
            明日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="
              handleTimeChange('week');
              handleSearch();
            "
          >
            近7天
          </button>
        </view>
      </view>
      <!-- D. 列表 -->
      <view class="section-header">
        <text class="section-title">汇总统计</text>
        <view class="statistics-info">
          <text class="stat-item">计划总重量: {{ totalPlanWeight }} KG</text>
          <text class="stat-item">炉/批数: {{ totalBatchCount }}</text>
        </view>
      </view>
      <view
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 8rpx;
        "
      >
        <!-- 增加一行小字：每次最多查询100条数据，更多请滑动底部加载更多 -->
        <text
          class="section-subtitle"
          style="
            font-size: 20rpx;
            color: #999;
            text-align: center;
            width: 100%;
            display: block;
          "
          >每次最多查询100条数据，更多请滑动底部加载</text
        >
      </view>
      <scroll-view 
        class="table-scroll" 
        scroll-y 
        scroll-x
        @scrolltolower="onReachBottom"
        @scroll="handleTableScroll"
        ref="tableScroll"
      >
        <view class="table-scroll-container">
          <view class="table-scroll-wrapper">
            <view class="table-content">
              <view class="table-row header">
                <text class="table-cell">创建日期</text>
                <text class="table-cell table-cell-material">物料名称</text>
                <text class="table-cell">钢种</text>
                <text class="table-cell">规格</text>
                <text class="table-cell">重量(KG)</text>
                <text class="table-cell">数量(炉)</text>
                <text class="table-cell table-cell-customer">客户</text>
                <text class="table-cell">品名</text>
                <text class="table-cell">标准号</text>
                <text class="table-cell">工序</text>
              </view>
              <view
                v-for="(item, index) in detailTableData"
                :key="index"
                class="table-row"
              >
                <text class="table-cell" :title="item.createTime">{{
                  item.createTime ? dateHelperApi.formatDate(item.createTime) : "-"
                }}</text>
                <text class="table-cell table-cell-material" :title="item.materialName">{{
                  item.materialName || "-"
                }}</text>
                <text class="table-cell" :title="item.steelGradeName">{{
                  item.steelGradeName || "-"
                }}</text>
                <text class="table-cell" :title="item.prodSpec">{{
                  item.prodSpec || "-"
                }}</text>
                <text class="table-cell">{{ (item.planCount || 0).toFixed(3) }}</text>
                <text class="table-cell">{{ item.transCount || "-" }}</text>
                <text class="table-cell table-cell-customer" :title="item.custName">{{
                  item.custName || "-"
                }}</text>
                <text class="table-cell" :title="item.prodName">{{
                  item.prodName || "-"
                }}</text>
                <text class="table-cell" :title="item.standNo">{{
                  item.standNo || "-"
                }}</text>
                <text class="table-cell" :title="item.processName">{{
                  item.processName || "-"
                }}</text>
              </view>
            </view>
          </view>
          <!-- 横向滚动提示 -->
          <view
            class="scroll-hint"
            :class="{ show: showScrollHint }"
            v-if="showScrollHint"
          >
            <text class="hint-icon">→</text>
            <text>横向滑动查看更多信息</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { PlanLzApi } from "@/api/pp/planlz";
import { getProcessOptions } from "@/api/md/process";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "StockIn",
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
      },

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组
      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },
      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 表格数据
      detailTableData: [],
      detailLoading: false,
      // 加载状态
      loading: false,
      // 分页与刷新
      refreshing: false,
      pageNum: 1,
      hasMore: true,
      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,
      // 表格滚动提示
      showScrollHint: false,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 总计划量计算
    totalPlanWeight() {
      return this.detailTableData
        .reduce((total, item) => {
          return total + (parseFloat(item.planCount) || 0);
        }, 0)
        .toFixed(3);
    },
    // 炉/批数计算
    totalBatchCount() {
      return this.detailTableData.filter((item) => {
        // 有计划炉批数的数据
        if (item.transCount) {
          return true;
        }
        return false;
      }).length;
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.handleSearch();
    });
  },
  methods: {
    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;

        // 重新搜索数据
        this.handleSearch();
      }
    },

    /* 下拉刷新 = 重置 */
    onPullDownRefresh() {
      // 重置所有相关状态
      this.detailTableData = [];
      this.hasMore = true;
      this.pageNum = 1;
      this.refreshing = true;

      // 停止刷新状态
      setTimeout(() => {
        this.refreshing = false;
      }, 500);

      // 重新初始化时间范围并搜索 - 使用重置模式
      this.handleTimeChange(this.timeFilter);
      this.$nextTick(() => {
        this.handleSearch(false); // 明确传递false，确保是重置而不是加载更多
      });
    },
    /* 触底加载 */
    onReachBottom() {
      if (this.loading) return;
      this.pageNum++;
      this.handleSearch(true);
    },
    /* 搜索主表 */
    async handleSearch(loadMore = false) {
      if (!loadMore) {
        this.detailTableData = [];
        this.hasMore = true;
        this.pageNum = 1;
      }
      this.loading = true;

      // 构建查询参数
      const params = {
        pageNo: this.pageNum, // 注意：有些后端接口使用pageNo而不是pageNum
        pageSize: 10,
        processName: this.currentProcess.processName || "",
      };
      // 只有在时间范围有效时才添加时间参数
      if (this.timeRange.startTime && this.timeRange.endTime) {
        params.createTime = [this.timeRange.startTime, this.timeRange.endTime];
      }

      try {
        const response = await PlanLzApi.getPlanLzDetailPage(params);
        console.log("response:", response.data);
        if (response.code === 0) {
          const newData = response.data.list;
          if (loadMore && newData.length === 0) {
            // 加载更多但没有新数据，说明已经到底了
            this.hasMore = false;
            uni.showToast({
              title: "没有更多数据了",
              icon: "none",
            });
          } else {
            this.detailTableData.push(...newData);
            this.hasMore = response.data.list.length === 10;
          }
        } else {
          uni.showToast({
            title: response.message || "加载数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      setTimeout(() => {
        this.loading = false;
      }, 600);
    },
    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },

    /**
     * 处理表格滚动事件
     */
    handleTableScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      const scrollWidth = event.detail.scrollWidth;
      const clientWidth = event.detail.clientWidth;

      // 当可以横向滚动时显示提示
      if (scrollWidth > clientWidth) {
        // 滚动到最右边时隐藏提示
        if (scrollLeft >= scrollWidth - clientWidth - 10) {
          this.showScrollHint = false;
        } else {
          this.showScrollHint = true;
        }
      } else {
        this.showScrollHint = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.statistics-info {
  display: flex;
  gap: 30rpx;
}

.stat-item {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

/* 表格滚动容器 */
.table-scroll-container {
  overflow-x: auto;
  background-color: #fff;
}

/* 表格滚动提示 */
.scroll-hint {
  text-align: center;
  padding: 20rpx;
  font-size: 24rpx;
  color: #999;
  background-color: #f9f9f9;
  border-bottom: 1rpx solid #e5e5e5;
}

/* 表格样式 */
.table-content {
  min-width: 1200rpx;
}

.table-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e5e5e5;
  
  &:last-child {
    border-bottom: none;
  }
}

.table-cell {
  flex: 1;
  padding: 20rpx 15rpx;
  text-align: center;
  font-size: 26rpx;
  color: #333;
  border-right: 1rpx solid #f0f0f0;
  min-width: 120rpx;
  
  &:last-child {
    border-right: none;
  }
}

.header .table-cell {
  background-color: #f8f8f8;
  font-weight: 700;
  color: #333;
  font-size: 32rpx;
  padding: 20rpx 15rpx;
  min-height: 90rpx;
}

/* 表格内容字体优化 */
.table-row:not(.header) .table-cell {
  font-size: 30rpx !important;
  font-weight: 500;
  padding: 18rpx 15rpx;
  min-height: 85rpx;
  color: #1a1a1a;
}

/* 客户列样式 - 增加显示宽度 */
.table-cell-customer {
  flex: 2.5;
  min-width: 300rpx;
}

/* 物料名称列样式 - 增加显示宽度 */
.table-cell-material {
  flex: 2;
  min-width: 200rpx;
}

/* 工序选择器容器 */
.process-picker-container {
  flex: 1;
  margin-left: 20rpx;
}

/* 工序选择器样式 */
.process-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e1e5e9;
  min-height: 80rpx;
  transition: all 0.3s ease;
}

.process-picker:active {
  background-color: #f8f9fa;
  border-color: #007aff;
}

/* 工序显示文本 */
.process-display {
  flex: 1;
  font-size: 30rpx;
  color: #333333;
  font-weight: 500;
  text-align: center;
  margin-right: 16rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 下拉箭头 */
.picker-arrow {
  color: #007aff;
  font-size: 28rpx;
  font-weight: bold;
  transition: transform 0.3s ease;
}

/* 表单项目样式优化 */
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 20rpx;
}

.form-label {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  margin-right: 20rpx;
  min-width: 120rpx;
  white-space: nowrap;
}
</style>
